var courseTab = (function ($, initTools) {
    // 节点
    var $courseTab = $(".J_CourseTab"),
        $courseItemList = $(".course-item-list"),
        $courseCardList = $(".course-card-list");
    // 数据
    var courseData = $.parseJSON($("#courseData").html()),
        courseFieldData = $.parseJSON($("#courseFieldData").html());
    // 模板
    var tabItemTpl = $("#tabItemTpl").html(),
        cardTpl = $("#cardTpl").html();

    // 缓存
    var  htmlCache = {};

    var init = function () {
        bindEvent();
        render();
    }
    function render() {
        $courseItemList.html(renderTab(courseFieldData));
        $courseCardList.html(renderList(courseData));
    }
    function renderTab(data) {
        /**
         * 模板拼接
         */
        var list = '';
        list += initTools.tplReplace(tabItemTpl, {
            styleClass: 'course-item-lk lk-current',
            field: 'all',
            fieldName: '全部'
        })
        data.forEach(function (item, index) {
            list += initTools.tplReplace(tabItemTpl, {
                styleClass: 'course-item-lk',
                field: item.field,
                fieldName: item.field_name
            })
        })
        return list;
    }



    function bindEvent() {
        /**
         * 事件代理
         */
        $courseTab.on('click', '.course-item-lk', onTabClick);
    }
    function onTabClick() {
        var $this = $(this),
            index = $this.parent().index(),
            field = $this.attr('data-field');
            console.log(field);
        pageChange(field);
        tabChange($this);
    }
    function tabChange(target) {
        target.addClass('lk-current')
            .parent()
            .siblings()
            .children('.course-item-lk')
            .removeClass('lk-current');
    }
    function pageChange(field) {
        const newData = _filterData(field);
        $courseCardList.html(renderList(newData,field));
    }
    function _filterData(field) {
        return courseData.filter(function (item) {
            if (field === "all") {
                return true;
            }
            return item.field === field;
        })
    }
    function renderList(data,field) {
        if(!htmlCache[field]){
            var list = "";
            data.forEach(function (item) {
                list += initTools.tplReplace(cardTpl, {
                    id: item.id,
                    courseName: item.course_name,
                    price: item.price,
                    img: item.img
                })
            });
            htmlCache[field] = list;
            console.log('from renderList');
        }else{
            console.log('from cache');
        }
        return htmlCache[field];
    }
    return {
        init: init
    }
})(jQuery, initTools);